package com.group.itms.routes.services;

import android.content.Context;
import android.os.Looper;
import android.util.Log;

import com.group.itms.routes.ThisApplication;
import com.group.itms.routes.services.SyncService.SyncListener;

public class SyncManager {

	private static final String TAG = "SyncManager";

	private static SyncManager sInstance;

	private volatile SyncService mSyncService;
	private SyncListener mPendingListener;

	private Object mLock = new Object();
	
	private SyncCallbacks mCallback = new SyncCallbacks() {

		@Override
		public void onSyncStart(SyncService service) {
			synchronized (mLock) {
				mSyncService = service;
				if (mPendingListener != null) {
					registerSyncListener(mPendingListener);
					mPendingListener = null;
				}
			}
		}

		@Override
		public void onSyncStop(SyncService service) {
			synchronized (mLock) {
				mSyncService = null;
			}
		}

		@Override
		public void onSyncError(Exception e) {
			Log.e(TAG, "Error in syncservice", e);
		}
	};

	private SyncManager() {
		ThisApplication.getInstance().putAttribute(
				SyncService.SYNC_MANAGER_CALLBACK_KEY, mCallback);
	}

	public static SyncManager getInstance() {
		if (sInstance == null) {
			sInstance = new SyncManager();
		}
		return sInstance;
	}

	public synchronized boolean startSync() {
		if (isSyncing()) {
			Log.d(TAG, "Synchronization is already in progress");
			return false;
		}
		Context appCtx = ThisApplication.getInstance();
		appCtx.startService(SyncService.getIntent());
		return true;
	}

	public boolean isSyncing() {
		return mSyncService != null; // atomic, since it's volatile ;)
	}

	public void registerSyncListener(SyncListener listener) {
		synchronized (mLock) {
			if (mSyncService != null) {
				mSyncService.registerSyncListener(listener, Looper.getMainLooper());
			} else {
				mPendingListener = listener;
			}
		}
	}

	public void unregisterSyncListener(SyncListener listener) {
		synchronized (mLock) {
			if (mSyncService != null) {
				mSyncService.unregisterSyncListener(listener);
			}
		}
	}
}
